package com.tal.pad.orc.base.utils;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.*;

public class LogUtils {
    private static LogUtils instance = null;

   public static LogUtils getLogUtils() {
       return instance;
   }

   public static void setLogUtils(LogUtils instance) {
       LogUtils.instance = instance;
   }

    Logger logger;
    FileHandler fileHandler;

    public LogUtils(String filePath){
        logger = Logger.getLogger(LogUtils.class.getName());
        String fileName = SimpleDateFormat.getDateInstance().format(new Date()) +".log";
        File file = new File(filePath, fileName);
        try {
            if (!file.exists()){
                boolean newFile = file.createNewFile();
            }
            d(logger.getName(),"filePath:"+filePath + " fileName:"+fileName);
            fileHandler = getFileHandler(filePath, fileName);
            logger.addHandler(fileHandler);
//            ConsoleHandler consoleHandler = new ConsoleHandler();
//            consoleHandler.setLevel(Level.ALL);
//            logger.addHandler(consoleHandler);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static FileHandler getFileHandler(String filePath, String fileName) throws IOException {
        FileHandler fileHandler = new FileHandler(filePath + fileName,true);
        fileHandler.setFormatter(new Formatter() {
            private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            public String format(LogRecord record) {
                StringBuilder sb = new StringBuilder();
                String dataFormat = this.sdf.format(Long.valueOf(record.getMillis()));
                sb.append(dataFormat).append(" ");
                sb.append("level:").append(record.getLevel()).append(" ");
                sb.append(record.getMessage()).append("\n");

                return sb.toString();
            }
        });
        fileHandler.setLevel(Level.ALL);
        return fileHandler;
    }

    public  void info(String tag, String msg) {
        logger.log(Level.INFO, tag + ": " + msg);
        fileHandler.flush();

    }
    public  void e(String tag, String msg) {
        logger.log(Level.ALL, tag + ": " + msg);
        fileHandler.flush();
    }

    public  void w(String tag, String msg) {
        logger.log(Level.WARNING, tag + ": " + msg);
        fileHandler.flush();
    }


    public static void d(String tag, String msg) {
        System.out.println(tag + ": " + msg);
    }



}
